#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>

extern char **environ; 

void printEnv(){
    char **ep;
    for(ep = environ; *ep != NULL ;ep++){
        puts(*ep);
    }
}

int my_setenv(const char *name, const char *value, int overwrite){
    char *newEnv = NULL;
    if((getenv(name) != NULL) && (overwrite == 0)){
        return 0;
    }
    else{
        newEnv = malloc(strlen(name) + strlen(value) + 1);
        if (newEnv == NULL){
            printf("Error malloc %d %s\n", errno, strerror(errno));
            return -1;
        }
        strcpy(newEnv, name);
        strcat(newEnv, "=");
        strcat(newEnv, value);
        if(putenv(newEnv) != 0){
            printf("Error putenv %d %s\n", errno, strerror(errno));
            return -1;
        }
    }
    return 0;
}

int my_unsetenv(const char *name){
    char **ep, **i;

    for(ep = environ; *ep != NULL; ep++){
        if (strncmp(*ep, name, strcspn(*ep,"=")) == 0){
            printf("Find %s\n", *ep);
            i = ep;
            *i = *(i + 1);
            if(*(i) == NULL)
                break;
            i++;
            while(*(i + 1) != NULL){
                *i = *(i + 1);
                i++;
            }
        }       
    }
    return 0;
}

int main(){
    char *key = "NewKey";
    char *val = "NewVal";
    puts("Print env before add:");
    printEnv();
    if(my_setenv(key, val, 0) == -1){
        exit(EXIT_FAILURE);
    }
    puts("\nPrint env after add:");
    printEnv();
    if(my_setenv(key, "NewVal2", 1) == -1){
        exit(EXIT_FAILURE);
    }

    puts("\nPrint env after change:");
    printEnv();
    puts("\nPrint env after my_unsetenv:");
    my_unsetenv(key);
    printEnv();
    exit(EXIT_SUCCESS);

}